<?php
/**
 * ANTFW entrance
 *
 * @author $AUTHOR$
 * @since $DATE$
 * @version $ID$
 */

defined('APP_NAME') || die('Access denied');

/**
 * Check app status
 *
 * -1: closed
 * 0:  dev
 * 1:  debug
 * 2:  product
 */
defined('APP_STATUS') && -1 === APP_STATUS && die('Site closed');

/**
 * Define ANTFW_ROOT
 */
define('ANTFW_ROOT', __DIR__. DIRECTORY_SEPARATOR);

/**
 * Define APP_ROOT
 */
$trace = debug_backtrace();
$trace = realpath(dirname($trace[0]['file'])). DIRECTORY_SEPARATOR;
define('APP_ROOT', $trace);
unset($trace);

/**
 * Load const file
 */
require ANTFW_ROOT. 'const.inc.php';

/**
 * Load functions file
 */
require ANTFW_ROOT. 'functions.func.php';

/**
 * Load default setting
 */
$default = require ANTFW_ROOT. 'default.inc.php';

/**
 * Parse URI
 */
$uri = str_replace(APP_URL_PATH, '', trim($_SERVER['REQUEST_URI']));

// mime 
$mime = strtolower(substr($uri, strrpos($uri, '.')+1));
$keys = array_keys($default['mimes']);
if (!in_array($mime, $keys))
    $mime = 'html';
else
    $uri = substr($uri, 0, strrpos($uri, '.'));

// set header
header('content-type: '.$default['mimes'][$mime]. '; charset=utf-8');
define('MIME', $mime);
unset($mime, $keys);

if (substr($uri, -1) == '/')
    $uri = substr($uri, 0, -1);
$uri = explode('/', $uri);

// CONTROLLER
define('CONTROLLER', isset($uri[0]) && ($uri[0] = trim($uri[0]))? $uri[0]: $default['controller']);
// ACTION
define('ACTION', isset($uri[1]) && ($uri[1] = trim($uri[1]))? $uri[1]: $default['action']);
// $_GET
$_GET = array();
$keys = $values = array();
if (($count = count($uri)) > 2)
    for ($i = 2; $i < $count; $i++) {
        if (0 === $i%2)
            $keys[] = trim($uri[$i]);
        else
            $values[] = $uri[$i];
    }
if (count($keys) != count($values))
    $values[] = NULL;
if (count($keys) > 0)
    $_GET = array_combine($keys, $values);
// unset temp vars
unset($uri, $keys, $values, $count, $i, $default['controller'], $default['action']);

/**
 * Load app configure
 */
$config = array_merge($default, (array)require APP_ROOT. 'config/app.inc.php');

isset($config['controllers'][CONTROLLER]) && in_array(ACTION, $config['controllers'][CONTROLLER]) || halt(403, 'Access denied');

//unset temp vars
unset($config['controllers']);

config($config, DO_MERGE);

/**
 * Load dbal/controller/model/view
 */
require ANTFW_ROOT. 'controller.class.php';
require ANTFW_ROOT. 'model.class.php';
require ANTFW_ROOT. 'view.class.php';

/**
 * App functions
 */
require APP_ROOT. 'functions.func.php';

/**
 * Load app common script
 */
require APP_ROOT. 'common.php';

/**
 * Start to run app controller
 */
call('controller.'. CONTROLLER. '.'. ACTION);
